/*
尽可能还原 Promise 中的每一个 API, 并通过注释的方式描述思路和原理.
*/
// 先实现promise的构造函数,promise的三大状态为pending,fulfilled,rejected
// 先简单实现promise的初始状态，在观察
let PENDING = 'pending'
let FULFILLED = 'fulfilled'
let REJECTED = 'rejected'
 
function myPromise(fn) {
	this.value = null;
	this.status = PENDING;
	this.fulfilledCallbacks = [];
	this.rejectedCallbacks = [];
 
	function resolve(value) {
		if (this.status === PENDING) {}
	}
 
	function reject(value) {
		if (this.status === PENDING) {}
	}
 
	// 执行回调函数
	try {
		fn(resolve, reject)
	} catch (e) {
		reject(e);
	}
}
// 执行完后，promise成功的回调放在reslove里，那reslove需要改变status的值，然后会改成fulfilled状态(即成功完成)，最后在回调函数中获取相应的数据
// 那么我们在resolve和reject中都应该改变他的状态 resolve即成功,reject即失败
function myPromise(fn) {
	this.value = null;
	this.status = PENDING;
	this.fulfilledCallbacks = [];
	this.rejectedCallbacks = [];
	function resolve(value) {
		if (this.status === PENDING) {
			this.status = FULFILLED;
			this.value = value;
			//执行回调方法
			this.fulfilledCallbacks.forEach(myFn => myFn(this.value))
		}
	}
 
	function reject(value) {
		if (this.status === PENDING) {
			this.status = REJECTED;
			this.value = value;
			//执行回调方法
			this.rejectedCallbacks.forEach(myFn => myFn(this.value))
		}
	}
 
}
myPromise.prototype.then = function(onFulfilled, onRejected) {
	//等待状态，则添加回调函数到栈中
	if (this.status === PENDING) {
		this.fulfilledCallbacks.push(() => {
			onFulfilled(this.value);
		});
		this.rejectedCallbacks.push(() => {
			onRejected(this.value);
		})
	}
	if (this.status === FULFILLED) {
		onFulfilled(this.value);
	}
 
	if (this.status === REJECTED) {
		onRejected(this.value)
	}
}
 
// 最后可以完整实现一个promise
let PENDING = 'pending'
let FULFILLED = 'fulfilled'
let REJECTED = 'rejected'
 
function myPromise(fn) {
	this.value = null;
	this.status = PENDING; //默认状态
	this.fulfilledCallbacks = [];
	this.rejectedCallbacks = [];
 
	function resolve(value) {
		if (this.status === PENDING) {
			this.status = FULFILLED;
			this.value = value;
			//执行回调方法
			this.fulfilledCallbacks.forEach(myFn => myFn(this.value))
		}
	}
 
	function reject(value) {
		if (this.status === PENDING) {
			this.status = REJECTED;
			this.value = value;
			//执行回调方法
			this.rejectedCallbacks.forEach(myFn => myFn(this.value))
		}
	}
 
	// 执行回调函数
	try {
		fn(resolve, reject)
	} catch (e) {
		reject(e);
	}
}
myPromise.prototype.then = function(onFulfilled, onRejected) {
	let that = this;
	//等待状态，则添加回调函数到栈中
	if (that.status === PENDING) {
		that.fulfilledCallbacks.push(() => {
			onFulfilled(that.value);
		});
		that.rejectedCallbacks.push(() => {
			onRejected(that.value);
		})
	}
	if (that.status === FULFILLED) {
		onFulfilled(that.value);
	}
 
	if (that.status === REJECTED) {
		onRejected(that.value)
	}
}
 
let thisreslove = new myPromise((resolve, reject) => {
	console.log('hello lagou');
	resolve(5);
});
thisreslove.then((res) => {
	console.log(res);
})
thisreslove.then(() => {
	console.log('success');
})